<?php
namespace App\Service\Xcx;

use App\Service\Xcx\BaseService as Service;

class AddressService extends Service
{
    //收货地址

    //列表
    public static function index($pas)
    {
        $db = self::dbConn(self::$dbAddress)->where('del', 0);
        if ($pas['uid']) {
            $db = $db->where('uid', $pas['uid']);
        }
        $total = $db->count();
        $res = $db->get();
        if (!count($res)) {
            return self::toback(-2, '没有数据');
        }
        $ary = [];
        foreach ($res as $v) {
            $ary[] = [
                'id' => $v->id, 'uid' => $v->uid,
                'accepter' => $v->accepter, 'phone' => $v->phone,
                'dizhi' => $v->dizhi, 'default' => $v->default,
            ];
        }
        return self::toback(0, '', $ary, $total);
    }

    //新增
    public static function add($pas)
    {
        $pas['addtime'] = $pas['uptime'] = toDate();
        self::dbConn(self::$dbAddress)->insertGetId($pas);
        return self::toback();
    }

    //修改
    public static function modify($id, $pas)
    {
        $res = self::dbConn(self::$dbAddress)->where('id', $id)->first();
        if (empty($res)) {
            return self::toback(-2, '没有数据');
        }
        $pas['uptime'] = toDate();
        self::dbConn(self::$dbAddress)->where('id', $id)->update($pas);
        return self::toback();
    }

    /**
     * 设置默认
     * @param int $id
     */
    public static function toDefault($id)
    {
        $res = self::dbConn(self::$dbAddress)->where('id', $id)->first();
        if (!$res) {
            return self::toback(-2, '没有数据');
        }
        self::dbConn(self::$dbAddress)
            ->where('uid', $res->uid)
            ->update(['default' => 0]);
        self::dbConn(self::$dbAddress)
            ->where('id', $id)
            ->update(['default' => 1]);
        return self::toback();
    }

    //删除
    public static function del($id)
    {
        $res = self::dbConn(self::$dbAddress)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return self::toback(-2, '属性不存在');
        }
        $up = self::dbConn(self::$dbAddress)->where('id', $id)
            ->update(['del' => 1, 'deltime' => toDate()]);
        if (!$up) {
            return self::toback(-2, 'error');
        }
        return self::toback();
    }
}